<template>
   <div id="all">
         <el-dialog title="高德地图坐标选择器" width="600px" top="20px" :visible.sync="show" :before-close="closeForm" append-to-body>
            <el-input id="keyword" size="small" suffix-icon="el-icon-location" v-model="address" autoComplete="off" clearable  placeholder="请输入搜索地址"></el-input>
            <div id="mapContainer"></div>
            <div slot="footer" class="dialog-footer">
              <el-button size="small" type="primary" @click="submit" >
                <span>确 定</span>
              </el-button>
              <el-button size="small" @click="closeForm">取 消</el-button>
            </div>
         </el-dialog>
    </div>
</template>

<script>
export default {
  name: 'index',
  props: {
      mapKey: {
        type: String,
        default: '5e1026117f9d0db212f49c257e216137'
      },
      show: {
          type: Boolean,
          default: false
      },
      address_detail:{
          type:String,
          default:null
      },
      picker:{
          type:String
      }
  },
  data () {
    let points =  this.address_detail ? JSON.parse(this.address_detail) : {lng:'',lat:'',address:''}
    return {
      lng:points.lng,
      lat:points.lat,
      zoom: 15,
      address: points.address,
    }
  },
  mounted() {
    this.loadScript()
  },
  methods: {
    //异步加载地图js
    loadScript() {
      var script = document.createElement("script");
      script.type = "text/javascript";
      window.initMap = () => {
        this.init()
      };
      script.src ="https://webapi.amap.com/maps?v=1.4.15&key=" +this.mapKey +"&callback=initMap"
      document.body.appendChild(script);
    },
    init() {
        const self = this
        AMap.plugin(['AMap.CitySearch', 'AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Geocoder', 'AMap.ToolBar'], function () {
        var citySearch = new AMap.CitySearch()
        var map
        var placeSearch

        if(self.lng && self.lat){
            var map=new AMap.LngLat(self.lng, self.lat);
        }

        citySearch.getLocalCity(function (status, result) {
          if (status === 'complete' && result.info === 'OK') {
            map = new AMap.Map("mapContainer", {
                view:new AMap.View2D({
                  resizeEnable: true,
                  zoom: self.zoom,//地图显示的缩放级别
                  center:map,
                  keyboardEnable: false,
                })
            });

            if(self.lng && self.lat){
                marker = new AMap.Marker({
                    icon:new AMap.Icon({            
                        image: '',
                        size: new AMap.Size(45, 65),  //图标所处区域大小
                        imageSize: new AMap.Size(45,65) //图标大小
                    }),
                    position: [self.lng,self.lat],
                    offset: new AMap.Pixel(-13, -30)
                });
                marker.setMap(map);
            }

            map.addControl(new AMap.ToolBar());
            let marker, geocoder
            AMap.event.addListener(map, "click", function(e) {
              if(marker != null) {
                marker.setMap(null)
              }
              marker = new AMap.Marker({
                icon:new AMap.Icon({            
                    image: '',
                    size: new AMap.Size(45, 65),  //图标所处区域大小
                    imageSize: new AMap.Size(45,65) //图标大小
                }),        
                position: e.lnglat,
                offset: new AMap.Pixel(-13, -30)
              });
              marker.setMap(map);
              self.lng = e.lnglat.lng
              self.lat = e.lnglat.lat
              if(!geocoder){
                geocoder = new AMap.Geocoder({
                  radius: 1000 //范围，默认：500
                });
              }
              geocoder.getAddress(e.lnglat, function(status, result) {
                if (status === 'complete'&&result.regeocode) {
                  var address = result.regeocode.formattedAddress;
                  self.address = address
                }else{
                  log.error('根据经纬度查询地址失败')
                }
              });
            })
            }
          })
          var autoOptions = {
            input: "keyword"
          };
          var autocomplete= new AMap.Autocomplete(autoOptions);
          AMap.event.addListener(autocomplete, "select", function(e){
              placeSearch = new AMap.PlaceSearch({
                  map:map
              })
              placeSearch.search(e.poi.name)
              self.address = e.poi.district+e.poi.name
              self.lng = e.poi.location.lng
              self.lat = e.poi.location.lat
          });
        })
    },
    submit(){
        let address = {address:this.address,lng:this.lng,lat:this.lat}
        this.$emit('update:address_detail', JSON.stringify(address))
        this.closeForm()
    },
    closeForm(){
        this.$emit('update:show', false)
    }
  }
}
</script>

<style scoped>
#mapContainer {
  width: 100%;
  margin-top:2px;
  height: 50vh;
}
</style>
